// 全局变量
var today = new Date();
var todayTxt = today.format('yyyy-MM-dd');

var MY_WASTE_DELIVERY = (function() {

	function loadItem(){
		//清除排序
		var  oTable = document.getElementById("dataTable");
		oTable.sortCol = -1;
		//重置全部排序图标
		$("after").css("opacity",0.3);
		$("before").css("opacity",0.3);

		var params = getParams();
		// 输入有误的情况下，退出
		if (!params){
			return false;
		}
		
		var $tbodySpecimenList = $('#tbodySpecimenList');
		$tbodySpecimenList.empty();
		
		WeKnow.loading();
		
		$.ajax({ 
	        type: "POST", 
	        url: "invs_waste_delivery.do/load", 
	        dataType: "json",
	        contentType:"application/json",
	        data: JSON.stringify(params),
	        async: true,//异步调用
	        success: function(data) {
	        	
	        	WeKnow.closeLoading();
	        	
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	
	        	if (data.errcode == 0) {
	        		var e = '';
	        		
	        		if ( 'datalist' in data && data.datalist.length == 0 ){
	        			WeKnow.errorMsg('没有查询到医疗机构数据');
	        			return;
	        		}
	        		
	        		$(data.datalist).each(function( idx,_a){
	        			e+='<tr class="pointer" ';
		        				e+= ' data-institution_id="' + _a.institutionId + '"';
		        				e+= ' data-institution_name="' + _a.institutionName + '"';
	        			e+='>';
        					// 诊所名
	        				e+='<td class="text-left">'+  _a.institutionName + '</td>';
        					// 登记次数
	        				e+='<td class="text-right">'+_a.registryCnt + '</td>';
	        				// 未处理申诉数 add by zhengxb 2019.11.28 -------------------------
	        				e+='<td class="text-right">'+ (_a.noAppealCnt==null?0:_a.noAppealCnt) + '</td>';
	        				// 状态
	        				e+='<td class="text-center">'+ (_a.checkSt==0?'正常': '<font style="color:red;">异常</font>')+'</td>';
        					// 操作
	        				e+='<td class="text-center"><button type="button" name="showDetail" class="btn btn-default btn-sm">查看</button></td>';
	        			e+='</tr>';
	        		});
	        		$tbodySpecimenList.append(e);
	        		
	        	} else if (data.errcode == -1 ) {
	        		WeKnow.errorMsg( data.errMsg );
	        	} else {
	        		WeKnow.systemMsg('查询失败，请重新登录后再试');
	        	}
	        }
		});
	}


	// 收集页面查询参数
	function getParams(){
		
		var data = getFromPar();//获取日期等共通输入参数
		
		if (!data){
			return data;
		}
		// 诊所名
		var institutionName = $.trim( $('#institutionName').val());
		if ( institutionName.length ){
			data.institutionName = institutionName;
		}
		// 登记状态
		var checkSt = $('#checkSt').val();
		if ( checkSt!=9 ){ //全部以外
			data.checkSt = $('#checkSt').val();
		}

		data.institutionTypeFirst = $('select[name="institutionTypeFirstScreen"]').val();//医疗机构类别

		return data;
	}
	
	// 收集页面查询参数
	function getDetailParams(){
		
		var data = getFromPar();//获取日期等共通输入参数
		if (!data){
			return data;
		}
		// 用户点了哪家机构
		data.institutionId = $('#institutionId').val();
		
		return data;
	}
	
	/** 获取页面输入参数 */
	function getFromPar(){
		var data = {};
		
		// 标本日期 from - to
		var $dtFrom = $('#dtFrom');
		if ( !$dtFrom.val().length ){
			WeKnow.errorMsg('请输入查询开始日期');
			$dtFrom.focus();
			return false;
		}
		
		var dtFrom = $dtFrom.val();
		if ( !MY_VALIDATOR.isDate(dtFrom,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询开始日期格式不正确');
			$dtFrom.focus();
			return false;
		}
		data.dtFrom = dtFrom;
		
		// 查询日期to
		var $dtTo = $('#dtTo');
		if ( !$dtTo.val().length ){
			WeKnow.errorMsg('请输入查询结束日期');
			$dtTo.focus();
			return false;
		}
		
		var dtTo = $dtTo.val();
		if ( !MY_VALIDATOR.isDate(dtTo,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询结束日期格式不正确');
			$dtTo.focus();
			return false;
		}
        if($dtFrom.val()>$dtTo.val()){
            WeKnow.errorMsg('开始时间不能大于结束时间');
            return false;
        }
		data.dtTo = dtTo;
		data.businessSubType = 201;// 业务区分
		
		if ( $('#onlyShowAppeal').prop('checked') ){
			data.onlyShowAppeal = 1;//只显示
		}
		
		return data;
	}
	
	// add by zhengxb 2019.6.21  end ---------------------------------------------------------
	return {
		loadItem:loadItem,
		getDetailParams:getDetailParams
	}
})();

$(document).ready(function() {
	
	// 页面初期数据查询
	MY_WASTE_DELIVERY.loadItem();
	
	//查询按钮按下
	$('#search').on('click',function(){
		MY_WASTE_DELIVERY.loadItem();
	});
	$('#checkSt').on('change',function(){
		MY_WASTE_DELIVERY.loadItem();
	});
	
	// 只显示有申诉的机构
	$('#onlyShowAppeal').on('click',function(){
		MY_WASTE_DELIVERY.loadItem();
	});

	$('select[name="institutionTypeFirstScreen"]').on('change',function(){
		MY_WASTE_DELIVERY.loadItem();
	});
	
	// 查看明细
	$('#tbodySpecimenList').on('click','button[name="showDetail"]',function(){
		var $that = $(this);
		var institutionId = $that.closest('tr').data('institution_id');
		$('#institutionId').val(institutionId);
		var institution_name  = $that.closest('tr').data('institution_name');
		// 设置明细页面的诊所名字
		$('#institution_name_dis').text(institution_name);
		$('#range_dis').text('('+ $('#dtFrom').val()+'至' + $('#dtTo').val()+')');
		$('.input-toggle').toggle();//显示部分切换
		
		// 数据查询
		var params = MY_WASTE_DELIVERY.getDetailParams();
		var $tHead  = $('#waste_thead');
		var $tbody = $('#waste_tbody');
		MY_WASTE_DELIVERY_COM.loadDetailItem(params,$tHead,$tbody);
	});
	
	// 回主页
	$('#backToWorkspace').on('click',function(){
		MY_WASTE_DELIVERY.loadItem();
		$('.input-toggle').toggle();//显示部分切换
	});
	
	// 处理申诉 OR 取消异常   注：申诉处理由于多个页面共用，故提炼成appeal.js
	$('#waste_tbody').on('click','button[name="check"],button[name="closeIllegal"]',function(){
		var $that = $(this);
		var $parentTr = $that.closest('tr');
		
		var illegalId = $parentTr.data('illegal_id');
		var originBtnName= $that.prop('name');
		
		// 数据查询
		var params = MY_WASTE_DELIVERY.getDetailParams();
		if(params){
            var $tHead = $('#waste_thead');
            var $tbody = $('#waste_tbody');

            // 更新用模态框
            MY_APPEAL.createModalWin
            (illegalId, originBtnName,
                function () {
                    MY_WASTE_DELIVERY_COM.loadDetailItem(params, $tHead, $tbody);
                }
            );
        }
	});
	
	// 显示申诉图片
	$('#waste_tbody').on('click','button[name="showAppealAtta"]',function(){
		var $that = $(this);
		var $parentTr = $that.closest('tr');
		
		var appealAtta = $parentTr.data('appeal_atta');
		var institutionId = $('#institutionId').val();
		// 显示交接单图片
		MY_SHOW_IMG.createShowImgModal(institutionId ,appealAtta);
	});
	
	// 显示图片
	$('#waste_tbody').on('click','td.show_img',function(){
		
		var $that = $(this).closest('tr');
		// 模态框显示诊所名，选定的日期
		$('#imageModalTitle').text($('#institution_name_dis').text() + ' ' + $that.data('serial_date'));
		// 显示交接单图片
		MY_SHOW_IMG.createShowImgModal($that.data('institution_id'),$that.data('receipt_img_id'));
	});
	
	$(".my_date_control" ).datepicker({
		changeMonth: true,
		changeYear: true,
        dateFormat: 'yy-mm-dd',//日期格式  
        yearSuffix: '年', //年的后缀
        showMonthAfterYear:true,//是否把月放在年的后面  
        maxDate: (function() {
        	return todayTxt;
        })(),//最大日期  
        yearRange: (function() {
        	// '1990:2010'
        	var year1 = '1900';
        	var year2 = today.getFullYear();
        	return year1 + ':' + year2;
        })(),
        monthNamesShort: ['01','02','03','04','05','06','07','08','09','10','11','12'],
        dayNamesMin: ['日','一','二','三','四','五','六'],
        onUpdatedDatepicker: function(_year, _month, _calendar) {
        	console.log('onUpdatedDatepicker');
        	var $c = $('div#ui-datepicker-div');
			$c.find('td[data-handler="selectDay"]').each(function(idx, d) {
				var $d = $(d);
				$d.css({'pointer-events': 'auto', 'opacity': 1});
    		});
        }
	});
});